package cn.pindao.t_upgrade_plugin;

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.core.content.FileProvider
import java.io.File
import java.io.IOException

class UpdateUtil {
    companion object {
        fun installApp(@NonNull context: Context, @NonNull apkFile: File) {
            if (!apkFile.exists()) {
                Toast.makeText(context, "安装包不存在，请重新下载，或去官网下载", Toast.LENGTH_SHORT).show()
                return
            }
            val cmd = "chmod 777 " + apkFile.absolutePath
            try {
                Runtime.getRuntime().exec(cmd);
            } catch (e: IOException) {
                e.printStackTrace()
            }
            val intent = Intent()
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.action = Intent.ACTION_VIEW
            /* 可调用getMIMEType()来取得文件MimeType */
            val type = "application/vnd.android.package-archive"
            /* 设置intent的file与MimeType */
            val uri: Uri
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                try {
                    val fileProviderName = context.packageName + ".fileProvider"
                    uri = FileProvider.getUriForFile(context, fileProviderName, apkFile)
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                } catch (ignore: Exception) {
                    ignore.printStackTrace()
                    Toast.makeText(context, "安装过程中出现异常，请去官网下载", Toast.LENGTH_SHORT).show()
                    return
                }
            } else {
                uri = Uri.fromFile(apkFile)
            }
            intent.setDataAndType(uri, type)
            context.applicationContext.startActivity(intent)
        }
    }
}

